package com.hhy.service.impl;

import com.hhy.entity.User;
import com.hhy.service.UserService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Description TODO
 * @Author hhy
 * @Date 2020/10/29 9:37
 */
public class UserServiceImplement implements UserService {
     static List<User> users = new ArrayList<>();

     static {
         users.add(new User("admin","123456",123456L,"无套餐",true));
     }

    //存储用户的信息
    File file = new File("user.txt");

    /**
     *
     * @param phone  手机号
     * @param password 密码
     * @return 是否登录成功
     */
    @Override
    public Boolean login(Long phone, String password) {
        List<User> userList = getUserList();
        if (userList==null) return false;
        for (User user : userList) {
            if (user.getPhoneNumber().equals(phone)&&user.getPassword().equals(password)){
                return true;
            }
        }

        return false;
    }


    /**
     * 序列化+注册
     */
    @Override
    public void registered(User user) {

        //文件不存在的话，那就新建一个
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //使用try（resource）
        try(FileOutputStream outputStream = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);
        ){
            //直接写入一个对象
            users.add(user);
            oos.writeObject(users);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //一波反序列化
    @Override
    public List<User> getUserList() {
        //如果文件不存在那就直接返回null
        if (!file.exists()) return users;

        try(FileInputStream fileInputStream = new FileInputStream(file);
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

        ){
            users = (List<User>) objectInputStream.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return users;
    }

    //通过手机号来拿到用户对象
    @Override
    public User getUserByPhoneNumber(Long phoneNumber) {
        List<User> userList = getUserList();
        if (userList==null) return null;
        for (User user : userList) {
            if (user.getPhoneNumber().equals(phoneNumber)){
                return user;
            }
        }
        return null;
    }

    @Override
    public boolean modifyPassword(Long phone,String newPassword) {

        //拿到用户，然后修改密码，重新写入
        User user = getUserByPhoneNumber(phone);
        //如果是用户存在，那就修改。
        if (userExist(user)){
            user.setPassword(newPassword);
            registered(user);
            return true;
        }else {
            //如果不存在那就是修改失败了
            return false;
        }
    }

    @Override
    public boolean deleteUser(Long phone) {
        User userByPhoneNumber = getUserByPhoneNumber(phone);
        //如果用户不存在，那就是删除失败了
        if (userByPhoneNumber==null){
            return false;
        }
        List<User> userList = getUserList();
        return userList.remove(userByPhoneNumber);
    }

    /**
     * @param user 用户对象
     * @return 用户是否存在 用户存在就是true，不存在就是false
     */
    private boolean userExist(User user){
        //先刷新一波
        users = getUserList();
        for (User user1 : users) {
            if (user1.getPhoneNumber().equals(user.getPhoneNumber())){
                return true;
            }
        }

        return false;
    }


    //因为这只是个人的通话详单，所以直接写死
    @Override
    public void generateExcel(User user) {
        double mola = 0.0;
        if(mealNum(user)){
            if (user.getCellTime()<5){
                mola = 0.0;
            }else {
                mola = (user.getCellTime()-5)*1.5;
            }
        }else {
            if (user.getCellTime()<35){
                mola = 0.0;
            }else {
                mola = (user.getCellTime()-35)*0.3;
            }
        }

        System.out.println("你好"+user);
        Workbook workbook = new HSSFWorkbook();
        //创建一张表
        Sheet sheet = workbook.createSheet(user.getUsername());
        Row row0 = sheet.createRow(0);
        row0.createCell(0).setCellValue("用户名称");
        row0.createCell(1).setCellValue("手机号");
        row0.createCell(2).setCellValue("通话时长");
        row0.createCell(3).setCellValue("已产生的费用");
        row0.createCell(4).setCellValue("当前余额");
        row0.createCell(5).setCellValue("当前套餐");

        Row row1 = sheet.createRow(1);
        row1.createCell(0).setCellValue(user.getUsername());
        row1.createCell(1).setCellValue(user.getPhoneNumber());
        row1.createCell(2).setCellValue(user.getCellTime());
        row1.createCell(3).setCellValue(mola);
        row1.createCell(4).setCellValue(user.getCallCast());
        row1.createCell(5).setCellValue(user.getMeal());

        //创建一个写入流
        try (FileOutputStream outputStream = new FileOutputStream(user.getPhoneNumber()+".xls")){
            workbook.write(outputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("文件创建成功了");

    }

    @Override
    public Double addMola(Long phone, Double mola) {
        User user = getUserByPhoneNumber(phone);
        //设置余额为剩下的钱，加当前充值的钱
        user.setCallCast(user.getCallCast()+mola);
        registered(user);
        return user.getCallCast();
    }

    @Override
    public String userCell(User user) {
        //首先是判断是否欠费
        Double callCast = user.getCallCast();
        Random random = new Random();
        if (callCast<0){
            return "话费不足,当前余额为"+callCast;
        }else {
            //本次通话时间
            int time = random.nextInt(4) + 2;
            int oldTime = user.getCellTime();
            //重新设置通话时间
            user.setCellTime(oldTime+time);
            //拿到总的通话时间
            int newTime = user.getCellTime();

            //如果是第一种套餐的话
            if (mealNum(user)){
                if (newTime<=5){
                    registered(user);
                    return "本次消费0元，通话时间"+time+"分钟";
                }
                user.setCallCast(user.getCallCast()-(time*1.5));
                registered(user);
                return "本次消费"+(time*1.5)+"元，通话时间"+time+"分钟";
            }else {
                if (newTime<=35){
                    registered(user);
                    return "本次消费0元，通话时间"+time+"分钟";
                }
                user.setCallCast(user.getCallCast()-(time*0.3));
                registered(user);
                return "本次消费"+(time*0.3)+"元，通话时间"+time+"分钟";
            }

        }
    }

    //套餐号是
    private boolean mealNum(User user){
        String meal = user.getMeal();
        if ((meal.charAt(0)+"").equals("3")){
            return true;
        }else return false;
    }


}
